package com.aspirecn.core.datacache;

import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;

import com.aspirecn.core.commons.Configuration;
import com.aspirecn.core.object.Haoduan;
import com.csvreader.CsvReader;

/**
 * 号段信息缓存 包括省份、城市以及它们之间的关系信息
 * 
 * @author wangxinning
 * 
 */
public class HaoduanCache extends BaseLocalCache {

	public final static Logger logger = Logger.getLogger(HaoduanCache.class);

	private Map<Integer, Haoduan> haoduanMap = new HashMap<Integer, Haoduan>();

	private static HaoduanCache instance = new HaoduanCache();

	private GEOCache geoCache = GEOCache.getInstance();

	private HaoduanCache() {

		this.dataFile = new File(Configuration.getInstance()
				.getDownloadFilePath() + File.separator + "haoduan.csv");
		load();
	}

	public static HaoduanCache getInstance() {
		return instance;
	}

	public void load() {

		if (!loading.getAndSet(true)
				&& Configuration.getInstance().switchHaoduanCache() && this.dataFile.exists()) {

			long start = System.currentTimeMillis();

			try {
				
				CsvReader reader = new CsvReader(this.dataFile.toString(), ',',
						Charset.forName("gbk"));

				while (reader.readRecord()) {

					Haoduan haoduan = new Haoduan();
					haoduan.setMobilePrefix(NumberUtils.toInt(reader.get(4)));
					int tianqiProvince = NumberUtils.toInt(reader.get(2));
					int tianqiCity = NumberUtils.toInt(reader.get(0));
					haoduan.setProvince(geoCache
							.getProvinceByTianqiID(tianqiProvince));
					haoduan.setCity(geoCache.getCityByTianqiID(tianqiCity));
					haoduanMap.put(haoduan.getMobilePrefix(), haoduan);
				}
				
				reader.close();

			} catch (Exception e) {
				logger.error("号段信息加载异常", e);
			}

			loading.set(false);
			long end = System.currentTimeMillis();
			updateFileDownloadTime();
			logger.info("号段信息加载完成，time=" + (end - start) + "ms,size="
					+ haoduanMap.size());

		} else {
			loading.set(false);
			logger.info("配置关闭，号段信息未加载");
		}
		
		loading.set(false);
	}

	@Override
	public void clear() {

		haoduanMap.clear();
	}

	@Override
	public void reload() {

		if (this.fileIsChange()) {
			this.load();
		} else {
			logger.info("没变化，号段信息未加载");
		}
	}	
	
	public Haoduan getHaoduan( int mobilePrefix )
	{
		return this.haoduanMap.get(mobilePrefix);
	}

	public static void main(String[] args) {
		HaoduanCache geoCache = HaoduanCache.getInstance();
		System.out.println(geoCache.getHaoduan(1389743));
	}
}